<template>
	<view>
		<view class="title">你可以在此为自己和朋友充值积分</view>

		<input :class="`input ${userError && 'error'}`" type="number" placeholder="在此粘贴或输入正确的用户ID" v-model="id" />

		<view class="tip" v-if="userError">抱歉，没有查询到该用户</view>

		<view class="options">
			<view :class="`item ${i == optionSel && 'sel'}`" v-for="(item, i) in options" :key="i" @tap="optionSel = i">支付{{ item.price }}元，获得{{ item.integral }}个积分</view>
		</view>

		<view :class="`button ${(!id || optionSel == -1) && 'lock'}`" @tap="integralRecharge" />
		<view class="title">提醒：输错ID充值的无法退回！请确认后再支付！</view>
	</view>
</template>

<script>
import * as wx from 'weixin-js-sdk';

export default {
	data() {
		return {
			id: '',
			options: [],
			optionSel: -1,
			userError: false
		};
	},
	onLoad() {
		const url = new URLSearchParams(window.location.search);
		const code = url.get('code');
		const openid = window.localStorage.getItem('openid');
		window.history.pushState({}, '', '');
		window.history.replaceState({}, '', '');
		if (!code) {
			let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfb07406bebbce810&redirect_uri=uri&response_type=code&scope=snsapi_base#wechat_redirect';
			url = new URL(url);
			// 获取查询参数对象
			const params = new URLSearchParams(url.search);
			// 删除旧的参数值（如果存在）
			params.delete('redirect_uri');
			// 添加新的参数值
			params.append('redirect_uri', window.location.href);
			// 更新查询字符串
			url.search = params.toString();
			window.location.href = url.href;
		} else if (!openid) {
			this.getOpenid(code);
			// 1.网络请求获取openid
			// 2.将openid缓存下来，避免多次调用缓存code失效
		} else {
			this.getIntegralPricing();
		}

		this.getWxConfig();

		wx.ready(function () {
			wx.updateAppMessageShareData({
				title: '点击进入积分中心后，直接输入你的用户ID，选择金额进行充值…', // 分享标题
				desc: '点击查看详情', // 分享描述
				link: window.location.origin, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: 'https://diandian-v1.oss-cn-zhangjiakou.aliyuncs.com/20241105/6729a6244db89.jpg' // 分享图标
			});
			wx.updateTimelineShareData({
				title: '点击进入积分中心后，直接输入你的用户ID，选择金额进行充值…', // 分享标题
				link: window.location.origin, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: 'https://diandian-v1.oss-cn-zhangjiakou.aliyuncs.com/20241105/6729a6244db89.jpg' // 分享图标
			});
		});
	},
	methods: {
		getOpenid(code) {
			this.$request({
				url: 'pay/getOpenid',
				data: { code }
			})
				.then((res) => {
					window.localStorage.setItem('openid', res.openid);
					this.getIntegralPricing();
				})
				.catch((err) => {
					// code 失效移除再次请求，有可能造成死循环
					const url = window.location;
					const params = new URLSearchParams(url.search);
					// 删除旧的参数值（如果存在）
					params.delete('code');
					// 添加新的参数值
					url.search = params.toString();
					window.location.href = '/';
				});
		},
		getIntegralPricing() {
			this.$request({
				url: 'pay/getIntegralPricing'
			}).then((res) => {
				this.options = res.data;
			});
		},
		integralRecharge() {
			if (!this.id || this.optionSel == -1) return;
			this.userError = false;
			this.$request({
				url: 'pay/integralRecharge',
				data: {
					user_id: this.id,
					integral: this.options[this.optionSel].integral,
					openid: window.localStorage.getItem('openid')
				}
			}).then((res) => {
				if (res.code == 200) {
					this.onBridgeReady(res.data);
				} else {
					this.userError = true;
				}
			});
		},
		onBridgeReady(data) {
			WeixinJSBridge.invoke('getBrandWCPayRequest', data, function (res) {
				if (res.err_msg == 'get_brand_wcpay_request:ok') {
					this.$showToast('支付成功', 'success', true, 200);
				}
			});
		},
		getWxConfig() {
			this.$request({
				url: 'tools/wxConfig',
				data: {
					url: window.location.href
				},
				hideLoading: true,
				autoHideLoading: false
			}).then((res) => {
				wx.config({
					appId: res.data.appId,
					timestamp: res.data.timestamp.toString(),
					nonceStr: res.data.nonceStr,
					signature: res.data.signature,
					jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
page {
	padding: 60rpx;
	box-sizing: border-box;
}

.title {
	margin: 20rpx;
	line-height: 38rpx;
	font-size: 26rpx;
	color: #335eff;
	text-align: center;
}

.input {
	width: 100%;
	height: 100rpx;
	margin: 0 0 20rpx;
	padding: 0 30rpx;
	box-sizing: border-box;
	border-radius: 10rpx;
	background-color: #fafafa;
	text-align: center;
	color: #333;
}
::v-deep .input-placeholder {
	color: #999;
}
.error {
	border: 1rpx solid #ee4545;
}

.tip {
	height: 40rpx;
	margin: 0 0 30rpx;
	line-height: 38rpx;
	font-size: 26rpx;
	color: #ee4545;
	display: flex;
	align-items: center;
	justify-content: center;
}

.options {
	margin: 0 0 40rpx;
	display: flex;
	flex-direction: column;
	gap: 20rpx;

	.item {
		width: 100%;
		height: 100rpx;
		padding: 0 30rpx;
		box-sizing: border-box;
		border-radius: 10rpx;
		border: 1rpx solid #d2d2d2;
		line-height: 48rpx;
		font-size: 32rpx;
		color: #333;
		font-weight: 400;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.sel {
		border: 2rpx solid #335eff;
		color: #335eff;
		font-weight: 500;
	}
}

.button {
	height: 94rpx;
	border-radius: 10rpx;
	background-color: #335eff;
	line-height: 48rpx;
	font-size: 34rpx;
	color: #fff;
	font-weight: 500;
	transition: opacity ease 300ms;
	display: flex;
	align-items: center;
	justify-content: center;

	&::after {
		content: '确定支付';
	}
}
.lock {
	opacity: 0.4;
}
</style>
